﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CPPEI.ETL.Domain.MessageAlert;
using CPPEI.ETL.Infrastructure.Email;

namespace CPPEI.ETL.Domain.Services
{
    public class LogService
    {
        public void Write(int level, string tag, string message)
        {
            Logger.Info(message);

            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.Log> rep = new EntityRepository<Entities.Log>(dbContext);
                Entities.Log log = new Entities.Log();
                log.Id = Guid.NewGuid();
                log.CreatedTime = DateTime.Now;
                log.Level = level;
                log.Message = message;
                log.Tag = tag;
                rep.Create(log);
                try
                {
                    dbContext.SaveChanges();
                }
                catch (Exception ex)
                {

                }
            }
        }

        public PagedList<Entities.Log> GetPagedList(int start, int limit)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.Log> rep = new EntityRepository<Entities.Log>(dbContext);
                List<Entities.Log> list = rep.Query().Skip(start).Take(limit).OrderByDescending(p => p.CreatedTime).ToList();
                int count = rep.Count();
                return new PagedList<Entities.Log>(true, 0, string.Empty, start, limit, count, list);
            }
        }

        public const int TaskExecLogModeAuto = 1;
        public const int TaskExecLogModeManual = 2;
        public const int TaskExecLogModeReexec = 3;
        public const int TaskExecLogResultSuccess = 1;
        public const int TaskExecLogResultFailure = 2;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="taskName"></param>
        /// <param name="taskId"></param>
        /// <param name="result"></param>
        /// <param name="mode"></param>
        /// <param name="message"></param>
        public static void WriteTaskExecLog(
            string taskName,
            Guid taskId,
            int result,
            int mode,
            string message)
        {
            /*	[Id] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY, 
    [TaskId] UNIQUEIDENTIFIER NULL, 
    [Result] INT NULL, 
    [Message] TEXT NULL, 
    [CreatedTime] DATETIME NULL, 
    [TaskName] VARCHAR(64) NULL, 
    [Mode] INT NULL*/

            try
            {
                using (EtlDbContext dbContext = new EtlDbContext())
                {
                    SqlConnection connection = dbContext.Database.Connection as SqlConnection;
                    connection.Open();
                    SqlCommand command = connection.CreateCommand();
                    command.CommandText = "Insert into ETL_TaskExecLog (Id,TaskId,Result,Message,CreatedTime,TaskName,Mode) values (@Id,@TaskId,@Result,@Message,@CreatedTime,@TaskName,@Mode)";
                    SqlParameter pId = new SqlParameter("@Id", Guid.NewGuid());
                    SqlParameter pTaskId = new SqlParameter("@TaskId", taskId);
                    SqlParameter pResult = new SqlParameter("@Result", result);
                    SqlParameter pCreatedTime = new SqlParameter("@CreatedTime", DateTime.Now);
                    SqlParameter pMessage = new SqlParameter("@Message", message);
                    SqlParameter pMode = new SqlParameter("@Mode", mode);
                    SqlParameter pTaskName = new SqlParameter("@TaskName", taskName);

                    command.Parameters.Add(pId);
                    command.Parameters.Add(pTaskId);
                    command.Parameters.Add(pResult);
                    command.Parameters.Add(pCreatedTime);
                    command.Parameters.Add(pMessage);
                    command.Parameters.Add(pMode);
                    command.Parameters.Add(pTaskName);
                    command.ExecuteNonQuery();
                    //错误提醒
                    if (result == TaskExecLogResultFailure)
                    {
                        string runmodestr = GetRunModeName(mode);
                        var _emailhelper = new EmailAlert();
                        _emailhelper.SendEmail(dbContext, taskName, (DateTime)pCreatedTime.Value, runmodestr, message);
                        var _smshelper = new SMSAlert();
                        _smshelper.SendSMS(dbContext, taskName, (DateTime)pCreatedTime.Value, runmodestr);
                    }
                    dbContext.SaveChanges();
                }
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>
        /// 获取运行状态
        /// </summary>
        /// <param name="runMode"></param>
        /// <returns></returns>
        private static string GetRunModeName(int runMode)
        {
            var str = "";
            switch (runMode)
            {
                case 1:
                    str = "自动";
                    break;
                case 2:
                    str = "手动";
                    break;
                case 3:
                    str = "重新执行";
                    break;
            }
            return str;
        }
    }
}
